package ltd.hxya.novel.crawl.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import ltd.hxya.novel.common.config.ThreadPoolConfig;
import ltd.hxya.novel.common.constant.redis.RedisConstant;
import ltd.hxya.novel.common.utils.RedisUtils;
import ltd.hxya.novel.crawl.bean.CrawlVo;
import ltd.hxya.novel.crawl.service.CrawlTaskService;
import ltd.hxya.novel.crawl.service.ICrawlSourceService;
import ltd.hxya.novel.crawl.service.impl.CrawlTaskServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Aspect
@Component
public class CrawlAspect {

    @Autowired
    private ICrawlSourceService crawlSourceService;

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    @Autowired
    private RedisUtils redisUtils;

    @Pointcut("execution(* ltd.hxya.novel.crawl.service.impl.CrawlTaskServiceImpl.*(..))")
    public void crawlSource() {
    }

    @Around(value = "crawlSource()")
    public void crawlSourceHandler(ProceedingJoinPoint joinPoint) throws Throwable {
        if (CrawlTaskServiceImpl.defaultCrawlThread.get() == null) {
            CrawlVo crawlVo = crawlSourceService.defaultCrawlSource();
            CrawlTaskServiceImpl.defaultCrawlThread.set(crawlVo);
        }
        if (CollectionUtils.isEmpty(CrawlTaskServiceImpl.threadLocal.get())) {
            List<CrawlVo> crawlVoList = crawlSourceService.crawlSourceList();
            CrawlTaskServiceImpl.threadLocal.set(crawlVoList);
        }
        String json = redisUtils.get(RedisConstant.CHAPTER_FILTER_KEYWORD_KEY);
        List<String> filterWord = JSON.parseObject(json, new TypeReference<List<String>>() {
        });
        CrawlTaskServiceImpl.filterWordThreadLocal.set(filterWord);
        joinPoint.proceed();
    }
}
